import pygame
import math

class Button:
    def __init__(self, x, y, width, height, text, font_size=36, color=(100, 100, 100)):
        self.rect = pygame.Rect(x, y, width, height)
        self.text = text
        self.color = color
        self.hover_color = tuple(min(c + 30, 255) for c in color)
        self.disabled_color = tuple(max(c - 50, 0) for c in color)
        self.font = pygame.font.Font(None, font_size)
        self.enabled = True
        self.hover = False

    def draw(self, screen):
        # 选择颜色
        if not self.enabled:
            color = self.disabled_color
        elif self.hover:
            color = self.hover_color
        else:
            color = self.color

        # 绘制按钮背景
        pygame.draw.rect(screen, color, self.rect, border_radius=10)
        pygame.draw.rect(screen, tuple(max(c - 40, 0) for c in color), 
                        self.rect, 3, border_radius=10)

        # 绘制文本
        text_surface = self.font.render(self.text, True, (255, 255, 255))
        text_rect = text_surface.get_rect(center=self.rect.center)
        screen.blit(text_surface, text_rect)

    def handle_event(self, event):
        if not self.enabled:
            return False

        if event.type == pygame.MOUSEMOTION:
            self.hover = self.rect.collidepoint(event.pos)
        elif event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:
            return self.rect.collidepoint(event.pos)
        return False

class LevelButton(Button):
    def __init__(self, x, y, width, height, level, font_size=36):
        super().__init__(x, y, width, height, level.name, font_size)
        self.level = level
        self.star_color = (255, 215, 0)  # 金色
        self.star_size = 20

    def draw(self, screen):
        super().draw(screen)

        # 绘制星星
        star_y = self.rect.bottom + 10
        for i in range(3):
            star_x = self.rect.centerx + (i - 1) * (self.star_size * 1.5)
            if i < self.level.stars:
                self._draw_star(screen, star_x, star_y, self.star_color)
            else:
                self._draw_star(screen, star_x, star_y, (100, 100, 100))

        # 绘制最高分
        if self.level.high_score > 0:
            score_text = self.font.render(f"最高分: {self.level.high_score}", 
                                        True, (255, 255, 255))
            score_rect = score_text.get_rect(
                centerx=self.rect.centerx,
                top=star_y + self.star_size + 5
            )
            screen.blit(score_text, score_rect)

    def _draw_star(self, screen, x, y, color):
        """绘制星星"""
        points = []
        for i in range(5):
            # 外部点
            angle = math.pi * 2 * i / 5 - math.pi / 2
            points.append((
                x + math.cos(angle) * self.star_size,
                y + math.sin(angle) * self.star_size
            ))
            # 内部点
            angle += math.pi / 5
            points.append((
                x + math.cos(angle) * (self.star_size * 0.4),
                y + math.sin(angle) * (self.star_size * 0.4)
            ))
        pygame.draw.polygon(screen, color, points)

class LevelSelector:
    def __init__(self, screen_width, screen_height, level_manager):
        self.screen_width = screen_width
        self.screen_height = screen_height
        self.level_manager = level_manager
        self.buttons = []
        self.create_buttons()
        
        # 导航按钮
        btn_width = 100
        btn_height = 40
        self.prev_button = Button(20, screen_height - 60, btn_width, btn_height, 
                                "上一页", color=(70, 70, 70))
        self.next_button = Button(screen_width - 120, screen_height - 60, 
                                btn_width, btn_height, "下一页", color=(70, 70, 70))
        self.back_button = Button(20, 20, btn_width, btn_height, 
                                "返回", color=(70, 70, 70))

        # 页面控制
        self.buttons_per_page = 6
        self.current_page = 0
        self.update_navigation_buttons()

    def create_buttons(self):
        """创建关卡按钮"""
        button_width = 200
        button_height = 80
        margin = 30
        buttons_per_row = 3
        
        for i, level in enumerate(self.level_manager.levels):
            row = (i // buttons_per_row)
            col = (i % buttons_per_row)
            
            x = self.screen_width // 4 + col * (button_width + margin)
            y = 150 + row * (button_height + margin * 2)
            
            button = LevelButton(x, y, button_width, button_height, level)
            button.enabled = self.level_manager.is_level_unlocked(i)
            self.buttons.append(button)

    def update_navigation_buttons(self):
        """更新导航按钮状态"""
        total_pages = (len(self.buttons) - 1) // self.buttons_per_page + 1
        self.prev_button.enabled = self.current_page > 0
        self.next_button.enabled = self.current_page < total_pages - 1

    def draw(self, screen):
        """绘制关卡选择界面"""
        # 绘制背景
        screen.fill((50, 50, 50))
        
        # 绘制标题
        font = pygame.font.Font(None, 64)
        title = font.render("选择关卡", True, (255, 255, 255))
        title_rect = title.get_rect(centerx=self.screen_width // 2, top=50)
        screen.blit(title, title_rect)
        
        # 绘制当前页的按钮
        start_idx = self.current_page * self.buttons_per_page
        end_idx = min(start_idx + self.buttons_per_page, len(self.buttons))
        for button in self.buttons[start_idx:end_idx]:
            button.draw(screen)
        
        # 绘制导航按钮
        self.prev_button.draw(screen)
        self.next_button.draw(screen)
        self.back_button.draw(screen)

    def handle_event(self, event):
        """处理用户输入"""
        if event.type in (pygame.MOUSEBUTTONDOWN, pygame.MOUSEMOTION):
            # 检查导航按钮
            if self.prev_button.handle_event(event):
                if self.current_page > 0:
                    self.current_page -= 1
                    self.update_navigation_buttons()
                return None
            
            if self.next_button.handle_event(event):
                total_pages = (len(self.buttons) - 1) // self.buttons_per_page + 1
                if self.current_page < total_pages - 1:
                    self.current_page += 1
                    self.update_navigation_buttons()
                return None
            
            if self.back_button.handle_event(event):
                return "back"
            
            # 检查关卡按钮
            start_idx = self.current_page * self.buttons_per_page
            end_idx = min(start_idx + self.buttons_per_page, len(self.buttons))
            for i, button in enumerate(self.buttons[start_idx:end_idx], start_idx):
                if button.handle_event(event):
                    if button.enabled:
                        self.level_manager.current_level_index = i
                        return "start_game"
            
        return None